<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>门店商品</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="{{asset('/layuiadmin/layui/css/layui.css')}}" media="all">
  <link rel="stylesheet" href="{{asset('/layuiadmin/style/admin.css')}}" media="all">
  <link rel="stylesheet" href="{{asset('/layuiadmin/layui/css/formSelects-v4.css')}}" media="all">
  <style>
    .edit{background-color: #ed9c3a;}
    .shenhe{background-color: #429488;}    
    .see{background-color: #7cb717;} 
    .cur{color:#009688;}
    .del {background-color: #e85052;}    /*.laytable-cell-1-school_icon{height:100%;}*/
    .yname{
          font-size: 13px;
          color: #444;
        }
        .storebox{
          height:200px;
          overflow-y: auto;
          z-index: 999;
          position: absolute;
          left: 0px;
          top: 60px;
          width:298px;
          background-color:#ffffff;
          border: 1px solid #ddd;
        }
        .storebox .list{
          height:38px;line-height: 38px;cursor:pointer;
          padding-left:10px;
        }
        .storebox .list:hover{
          background-color:#eeeeee;
        }
        .storeboxCopy{
          height:200px;
          overflow-y: auto;
          z-index: 999;
          position: absolute;
          left: 0px;
          top: 60px;
          width:298px;
          background-color:#ffffff;
          border: 1px solid #ddd;
        }
        .storeboxCopy .list{
          height:38px;line-height: 38px;cursor:pointer;
          padding-left:10px;
        }
        .storeboxCopy .list:hover{
          background-color:#eeeeee;
        }
        
        .importstorebox{
          height:200px;
          overflow-y: auto;
          z-index: 999;
          position: absolute;
          left: 0px;
          top: 60px;
          width:298px;
          background-color:#ffffff;
          border: 1px solid #ddd;
        }
        .importstorebox .list{
          height:38px;line-height: 38px;cursor:pointer;
          padding-left:10px;
        }
        .importstorebox .list:hover{
          background-color:#eeeeee;
        }
        .batchedit .layui-table-cell{
          height:40px;
          line-height:40px;
        }
  </style>
</head>
<body>

  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">

        <div class="layui-fluid">
          <div class="layui-row layui-col-space15">
            <div class="layui-col-md12" style="margin-top:0px">
              <div class="layui-card"> 
                <div class="layui-card-header">商品列表</div>

                <div class="layui-card-body">
                  <div class="layui-btn-container" style="font-size:14px;display:flex">

                    <div class="layui-form" lay-filter="component-form-group" style="margin-right:0;display: flex">
                      <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left:0;border-radius:5px">
                            <text class="yname">数据来源</text>
                            <select name="scource" id="scource" lay-filter="scource">
                                <option value="1">商品信息库</option>
                                <option value="2">门店商品信息</option>
                            </select>
                        </div>
                      </div>
                      <div class="layui-form-item storename" style="display:none">
                        <div class="layui-input-block" style="margin-left:5px;border-radius:5px;width:190px;">
                          <text class="yname">门店名称</text>
                          <input type="text" style="border-radius:5px" name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入门店名称" class="layui-input inputstore">
                          <div class="storebox" style='display: none'></div>
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left:5px;border-radius:5px;width:190px;">
                          <text class="yname">商品编码</text>
                          <input type="text" style="border-radius:5px" name="goods_code" autocomplete="off" placeholder="请输入商品编码" class="layui-input goods_code">
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <div class="layui-inline" style="display: inline-block;margin-top: 30px;margin-left: 15px;">
                          <button class="layui-btn layuiadmin-btn-list" lay-submit="" lay-filter="LAY-app-contlist-search" style="border-radius:5px;margin-top:-5px;margin-bottom: 0;height:36px;line-height: 36px;">
                              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                          </button>
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left:5px;border-radius:5px;display: flex">
                          <a class="layui-btn layui-btn-primary plCopy" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-top:25px;display: block;width: 122px;">一键复制</a>
                          <a class="layui-btn layui-btn-primary goodsCate" id="goodsCate" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-top:25px;display: block;width: 122px;">商品分类</a>
                          <a class="layui-btn layui-btn-primary addgoods" lay-href="" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-top:25px;display: block;width: 122px;">添加商品</a>
                          <a class="layui-btn layui-btn-primary batchEdit" id="batchEdit" style="background-color:#ed9c3a;border-radius: 5px;border:none;color:#fff;margin-top:25px;display: block;width: 122px;">批量修改</a>
                          <a class="layui-btn layui-btn-primary batchDel" id="batchDel" style="background-color:#e85052;border-radius: 5px;border:none;color:#fff;margin-top:25px;display: block;width: 122px;display:none">批量删除</a>
                        </div>
                      </div>
                    </div>
                    
{{--                    <div class="layui-form" lay-filter="component-form-group" style="width:300px;display: inline-block;">--}}
{{--                      <div class="layui-form-item">--}}
{{--                          <div class="layui-inline">--}}
{{--                            <div class="layui-input-inline">--}}
{{--                            <text class="yname">消息关键字</text>--}}
{{--                              <input type="text" name="id" placeholder="请输入消息关键字" autocomplete="off" class="layui-input">--}}
{{--                            </div>--}}
{{--                          </div>                          --}}
{{--                          --}}
{{--                          <div class="layui-inline">--}}
{{--                            <button class="layui-btn layuiadmin-btn-list" lay-submit="" lay-filter="LAY-app-contlist-search" style="margin-top:23px;border-radius:5px;margin-bottom: 0;height:36px;line-height: 36px;">--}}
{{--                              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>--}}
{{--                            </button>--}}
{{--                          </div>--}}
{{--                        </div>--}}
{{--                    </div>--}}
                    
                    

                  </div>
                  
                  <table class="layui-hide" id="test-table-page" lay-filter="test-table-page"></table>
                  
                 
                  <script type="text/html" id="imgTpl">
                    <img style="display: inline-block;height: 100%;" src= @{{d.img }}>
                  </script>
                  <script type="text/html" id="statusTpl">

                    @{{#  if(d.status == 1){ }}

                      <span>隐藏</span>

                    @{{#  } else { }}

                    <span class="cur">显示</span>

                    @{{#  } }}

                    </script>
                  <script type="text/html" id="table-content-list">
                    <a class="layui-btn layui-btn-normal layui-btn-xs edit" lay-event="edit">编辑商品</a>
                    <a class="layui-btn layui-btn-normal layui-btn-xs del" lay-event="del">删除</a>
                    
                  </script>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
  <!-- 一键复制门店搜索 -->
  <div id="copyTk" class="hide" style="display: none; background-color: #fff;padding: 15px;height:400px">
    <div class="layui-form" lay-filter="component-form-group" style="width:550px;margin-right:0;display: inline-block;">
      <div class="layui-form-item">
        <div class="layui-input-block" style="color: red;margin-left:0px">
          数据较多，最多选择10个。
        </div>  
        <div class="layui-input-block layui-inline" style="margin-left:5px;border-radius:5px;width:350px">
          <text class="yname">门店名称</text>
          <!-- <input type="text" style="border-radius:5px"name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入门店名称" class="layui-input inputstoreCopy">
          <div class="storeboxCopy" style='display: none'></div> -->
          <select name="storeNameSel" id="storeNameSel" xm-select="storeNameSel" xm-select-search="" xm-select-max="10">
          </select>
        </div>
        <div class="layui-inline">
          <div class="layui-input-block" style="margin-left:5px;border-radius:5px">
            <a class="layui-btn layui-btn-primary addPlGoods" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-top:20px;display: block;width: 122px;">确定</a>
          </div>
        </div>
      </div>
      
      </div>
  </div>
  <!-- 商品分类列表 -->
  <div id="openCatelist" style="display: none; background-color: #fff;">
    <div style="display:flex;margin: 10px 20px;">
        <a class="layui-btn layui-btn-primary buildCate" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-right:10px">添加分类</a>
    </div>
    <div style="margin: 0 20px;">
    <table id="cateTable" lay-filter="cateTable"></table>
    <script type="text/html" id="cateTable-content-list">
        <a class="layui-btn layui-btn-normal layui-btn-xs cateEditBtn" lay-event="cateEditBtn" style="border-radius:3.5px;">编辑</a>
    </script>
    </div>
</div>
<!-- 添加商品分类 -->
<div id="add_cate" class="hide" style="display: none;background-color: #fff;height: 300px;">
    <div class="layui-card-body" style="padding: 15px;">
        <div class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">分类名称:</label>
                <div class="layui-input-block">
                    <input type="text" placeholder="请输入分类名称" class="layui-input cate_title">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <div class="layui-footer" style="left: 0;">
                        <button class="layui-btn cateSubmit" style="border-radius:5px;margin-top:20px;width:100px">确定</button>
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" id="cateId">
    </div>
</div>
<div id="open_import" class="hide" style="display: none;background-color: #fff;height:300px">
  <div class="layui-card-body" style="padding:20px 30px">
    <div class="layui-form">
      <!-- <div class="layui-form-item">
        <text class="yname">门店名称</text>
        <input type="text" style="border-radius:5px" name="schoolname" lay-verify="schoolname2" autocomplete="off" placeholder="请输入门店名称" class="layui-input importstore">
        <div class="importstorebox" style='display: none'></div>
      </div> -->
      <div class="layui-form-item">
        <div class="layui-input-block layui-inline" style="margin-left:5px;border-radius:5px;width:300px;">
          <label class="yname">门店名称</label>
          <input type="text" style="border-radius:5px" name="schoolname" lay-verify="schoolname2" autocomplete="off" placeholder="请输入门店名称" class="layui-input importstore">
          <div class="importstorebox" style='display: none'></div>
        </div>
        <div class="layui-inline">
          <div class="layui-input-block" style="margin-left:5px;border-radius:5px">
            <a class="layui-btn layui-btn-primary batchEditStore" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-top:20px;display: block;width: 122px;">确定</a>
          </div>
        </div>
      </div>
      
    </div>
  </div>
</div>
<!-- 导入确认弹框表格 -->
  <div id="exportTable" class="hide" style="display: none; background-color: #fff;padding: 15px" class="batchedit">
      <div class="layui-form-item" style="width: 100%;display: flex;position: relative;">
        <form id= "uploadForm" >            
          <div class="layui-btn uploadFile" style="margin-right:20px;">选择所需上传文件</div>                  
          <input type="file" name="file" id="file" style="display: none;"/> 
          <input type="button" value="确定上传" id="UploadData" class="layui-btn"/>  
        </form>
        <a target="_blank" href="https://wanfutong.oss-cn-hangzhou.aliyuncs.com/1749193891.xlsx" class="layui-btn layui-btn-primary"  style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block;position: absolute;
    right: 0px;">下载模板</a>
      </div>
      <div style="display:flex;">
        <a class="layui-btn layui-btn-primary addbatchEdit" style="background-color:#ed9c3a;border-radius: 5px;border:none;color:#fff;margin-top:20px;display: block;width: 122px;">新增修改</a>
        <a class="layui-btn layui-btn-primary batchUploadEdit" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;margin-top:20px;display: block;width: 122px;margin-left:20px">一键修改</a>
      </div>
    
    <table id="previewTable" lay-filter="previewTable"></table>

    <!-- 操作列模板 -->
    <script type="text/html" id="operateTpl">
        @{{# if(d.uploaded){ }}
            <button class="layui-btn layui-btn-xs layui-btn-disabled" disabled>已修改</button>
        @{{# } else { }}
            <button class="layui-btn layui-btn-xs" lay-event="editClick">修改</button>
        @{{# } }}
         <button class="layui-btn layui-btn-xs del" lay-event="delClick">移除</button>
    </script>
  </div>
  <input type="hidden" class="store_id">
  <input type="hidden" class="store_idCopy">
  <input type="hidden" class="store_id_import">
  <input type="hidden" class="status">
  <input type="hidden" class="scource">
  
  <script src="{{asset('/layuiadmin/layui/layui.js')}}"></script> 
  <script src="{{asset('/layuiadmin/layui/jquery-2.1.4.js')}}"></script>
  <script src="{{asset('/layuiadmin/jquerysession.js')}}"></script>
  <script type="text/javascript" src="{{asset('/school/js/xlsx.full.min.js')}}"></script>
    <script>
    var token = localStorage.getItem("Usertoken");
    layui.config({
      base: '../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index','form', 'table','laydate','formSelects'], function(){
        var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,form = layui.form
            ,laydate = layui.laydate
            ,formSelects = layui.formSelects;

        var selectedIds = []; // 存储选中的行id
        var selectedValues = []; // 存储选中的行
        var table_data = [];
        
        // 未登录,跳转登录页面
        $(document).ready(function(){        
            if(token==null){
                window.location.href="{{url('/user/login')}}"; 
            }
        })

        // var pass =$.session.get('pass');
        // // 重置cookie有效期
        // var time = Date.parse(new Date()) + (5 * 60 * 1000);
        // $.session.set('time', time);
        
        var jccolsData =  [[
            {type: 'checkbox'}
            ,{field:'img', title: '封面图片',templet: '#imgTpl'}
            ,{field:'title', title: '商品标题'}
            ,{field:'cate_title', title: '分类名称'}
            ,{field:'num',  title: '数量'}   
            ,{field:'code',  title: '商品编码'}             
            ,{field:'price',  title: '价格'}                
            ,{field:'status',  title: '状态',templet: '#statusTpl'} 
            ,{field:'sort',  title: '排序'}   
            ,{field:'create_at',  title: '创建时间'}                
            ,{width:180,align:'center', fixed: 'right', toolbar: '#table-content-list',title: '操作'}
        ]];
        var mdcolsData =  [[
            {type: 'checkbox'}
            ,{field:'img', title: '封面图片',templet: '#imgTpl'}
            ,{field:'title', title: '商品标题'}
            ,{field:'store_id', title: '门店ID'}
            ,{field:'cate_title', title: '分类名称'}
            ,{field:'num',  title: '数量'}   
            ,{field:'code',  title: '商品编码'}             
            ,{field:'price',  title: '价格'}                
            ,{field:'status',  title: '状态',templet: '#statusTpl'} 
            ,{field:'sort',  title: '排序'}   
            ,{field:'create_at',  title: '创建时间'}                
            ,{width:180,align:'center', fixed: 'right', toolbar: '#table-content-list',title: '操作'}
        ]]
        var tableIns = table.render({
            elem: '#test-table-page'
            ,url: "{{url('/api/user/goods_list')}}"
            ,method: 'post'
            ,where:{
              token:token,  
              store_id:-1          
            }
            ,request:{
              pageName: 'p', 
              limitName: 'l'
            }
            ,page: true
            ,limits: [10, 20, 30, 40, 60, 80, 100, 120, 150, 180, 200] //每页条数的选择项
            ,cellMinWidth: 150
            ,cols: jccolsData
            ,parseData: function(res) {
                // 遍历数据，设置选中状态
                res.data.forEach(function(item) {
                    if (selectedIds.includes(item.id)) {
                        item.LAY_CHECKED = true;
                    }
                });
                return res;
            }
            ,response: {
                statusName: 'status' //数据状态的字段名称，默认：code
                ,statusCode: 1 //成功的状态码，默认：0
                ,msgName: 'message' //状态信息的字段名称，默认：msg
                ,countName: 't' //数据总数的字段名称，默认：count
                ,dataName: 'data' //数据列表的字段名称，默认：data
              } 
            ,done: function(res, curr, count){   
              $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
              // 手动触发复选框选中
              table_data = res.data;//初始化数据;此处接收的是当前页的这10条数据
              if (selectedIds.length > 0) {
                  for (var i = 0; i < selectedIds.length; i++) {
                      for (var j = 0; j < table_data.length; j++) {
                          if (selectedIds[i] == table_data[j].id) {//匹配上就设为选中
                              //回显checkbox
                              $('.layui-table tr[data-index=' + j + '] input[type="checkbox"]').attr("checked", "checked");
                              form.render('checkbox');
                          }
                      }
                  }
              }
            }

        });

        // var l_user_id = localStorage.getItem("l_user_id");
        // console.log(l_user_id,'l_user_id')
        // if(l_user_id && l_user_id == 1){
        //     $(".del").show();
        // }else{
        //     $(".del").hide();
        // }
        
         table.on('tool(test-table-page)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
          var e = obj.data; //获得当前行数据
          var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
          var tr = obj.tr; //获得当前行 tr 的DOM对象
          // localStorage.setItem('s_store_id', e.store_id);

          if(layEvent === 'del'){
            layer.confirm('确认删除此商品?',{icon: 2}, function(index){
              
              $.ajax({
                url : "{{url('/api/user/del_goods')}}",
                data : {token:token,id:e.id},
                type : 'post',
                success : function(data) {
                  if(data.status==1){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    layer.msg(data.message, {
                      offset: '50px'
                      ,icon: 1
                      ,time: 1000
                    });
                  }else{
                    layer.msg(data.message, {
                      offset: '50px'
                      ,icon: 2
                      ,time: 3000
                    });
                  }
                    
                },
              });

            });
          }else if(layEvent === 'edit'){
            sessionStorage.setItem('editGoods', JSON.stringify(e) );
            $(this).attr('lay-href',"{{url('/user/add_store_goods?')}}" + e.id);

          } 

          
        });

        table.on('checkbox(test-table-page)', function(obj) {
          var row = obj.data;
          if (obj.checked) {
            if (obj.type == 'one') {//勾选单条
              if (!selectedIds.includes(row.id)) {
                  selectedIds.push(row.id);
                  selectedValues.push(row);
              }
            }
            if (obj.type == 'all') {//勾选全部
                for (var i = 0; i < table_data.length; i++) {
                  if (!selectedIds.includes(table_data[i].id)) {
                      selectedIds.push(table_data[i].id);
                      selectedValues.push(table_data[i]);
                  }
                }
            }
          } else {
            if (obj.type == 'one') {
              // 从数组中移除
              var index = selectedIds.indexOf(row.id);
              if (index !== -1) {
                  selectedIds.splice(index, 1);
                  selectedValues.splice(index,1);
              }
            }else{
              for (var i = 0; i < selectedIds.length; i++) {
                for (var j = 0; j < table_data.length; j++) {
                    if (selectedIds[i] == table_data[j].id) {
                      selectedIds = selectedIds.filter(function (item) {
                        return item != selectedIds[i];
                      });
                    }
                }
              }
              for (var i = 0; i < selectedValues.length; i++) {
                for (var j = 0; j < table_data.length; j++) {
                    if (selectedValues[i].id == table_data[j].id) {
                      selectedValues = selectedValues.filter(function (item) {
                        return item.id != selectedValues[i].id;
                      });
                    }
                }
              }
            }
              
          }
          // console.log('当前选中ID：', selectedIds);
          // console.log('当前选中value：', selectedValues);
      });

        
        // 选择学校
        form.on('select(schooltype)', function(data){
          var type = data.value;
          
          //执行重载
          table.reload('test-table-page', {
            where: { 
              type: type
            }
            ,page: {
              curr: 1 //重新从第 1 页开始
            }
          });
        });
        
        
        $('.addgoods').click(function(){
          sessionStorage.removeItem('editGoods')
          $(this).attr('lay-href',"{{url('/user/add_store_goods')}}");
        });

        //监听搜索
        form.on('submit(LAY-app-contlist-search)', function(data){
          var scource = data.field.scource; 
          let store_id =  $('.store_id').val()    
          let code = $('.goods_code').val()
          let params = {}
          let colsData = []
          if(scource == 1){ //商品信息库
            params = {
              store_id:-1,
              token:token,
              code:code
            }
            colsData = jccolsData
            $('.batchDel').hide()
          
          }else{
            if(!store_id){
              layer.msg('请输入门店搜索！')
              return
            }
            params = {
              store_id:store_id,
              token:token,
              code:code
            }
            colsData = mdcolsData
            $('.batchDel').show()
          } 
          console.log(params,'params---')
          //执行重载
          tableIns.reload({
            cols:colsData,
            where: params
            ,page: {
              curr: 1 //重新从第 1 页开始
            }
          });
          selectedIds = [];
          selectedValues = [];
          storeSelData = [];
        });
      $(".inputstore").bind("input propertychange",function(event){
        let store_name = $(this).val();
        if (store_name.length == 0) {
          $('.storebox').html('');
          $('.storebox').hide();
        } else {
          $(".storebox").show();
          $('.storebox').html('');
          setTimeout(() => {
            $.post("{{url('/api/user/store_lists')}}",
              {
                token:token
                ,store_name:$(this).val()
                ,l:100
              },function(res){
                var html="";
                if(res.t==0){
                  $('.storebox').html('');
                }else{
                  for(var i=0;i<res.data.length;i++){
                    html+='<div class="list" data='+res.data[i].store_id+'>'+res.data[i].store_name+'</div>'
                  }
                  $(".storebox").show();
                  $('.storebox').html('');
                  $('.storebox').append(html);
                }
              },"json");
          }, 500);
        }
      });

      $(".storebox").on("click",".list",function(){
        $('.inputstore').val($(this).html());
        $('.store_id').val($(this).attr('data'));
        $('.storebox').hide();

        // table.reload('test-table-page', {
        //     where: {
        //         store_id:$(this).attr('data')
        //     }
        //     ,page: {
        //         curr: 1
        //     }
        // });
      });

      // 一键复制
      $('.plCopy').click(function(){
        if(selectedIds.length>0){
          layer.open({
            type: 1,
            title: '一键复制',
            area:  '600px',
            content: $('#copyTk'),
            success: function(){
              formSelects.config('storeNameSel', {
                  type: 'get',
                  searchUrl: "{{url('/api/user/store_lists?token=')}}"+token,  
                  searchName: 'store_name', // 自定义搜索内容的 key 值
                  delay: 500, // 搜索延迟时间，默认停止输入 500ms 后开始搜索
                  beforeSuccess: function(id, url, searchVal, result){
                      let arr = [];
                      //我要把数据外层的code, msg, data去掉
                      result = result.data;
                      for(var i=0;i<result.length;i++){
                          var data ={"value":result[i].store_id,"name":result[i].store_name};
                          arr.push(data);
                          // console.log(arr);
                      }
                    console.log(arr);
                      //然后返回数据
                      return arr;
                  },
                  beforeSearch: function (id, url, searchVal) {
                    if (!searchVal) {
                      // 如果搜索内容为空，就不触发搜索
                      return false
                    }
                    return true
                  },
              }).data('storeNameSel', 'server', {
                  url:"{{url('/api/user/store_lists?token=')}}"+token+"&l=100",
              })
            }
        });
        }else{
          layer.msg('请选择商品！')
        }
      })

      //一键复制-选择门店
      var storeSelData = []
      formSelects.on('storeNameSel', function (id, vals, val, isAdd, isDisabled) {
        console.log(1, '当前选中 id', id)
        console.log(2, '已选中值', vals)
        console.log(3, '点击值', val)
        console.log(4, '当前操作选中或取消', isAdd)
        console.log(5, '当前项是否是 disabled', isDisabled)

        if(isAdd==true){
          if(!storeSelData.includes(val.value)){
            storeSelData.push(val.value);
          }
        }else{
          if(storeSelData.includes(val.value)){
            storeSelData = storeSelData.filter(item => item !== val.value);
          }
        }
        console.log(storeSelData,'storeSelData-----')
      })

      $(".inputstoreCopy").bind("input propertychange",function(event){
        let store_name = $(this).val();
        if (store_name.length == 0) {
          $('.storeboxCopy').html('');
          $('.storeboxCopy').hide();
        } else {
          $.post("{{url('/api/user/store_lists')}}",
                  {
                    token:token
                    ,store_name:$(this).val()
                    ,l:100
                  },function(res){
                    var html="";
                    if(res.t==0){
                      $('.storeboxCopy').html('');
                    }else{
                      for(var i=0;i<res.data.length;i++){
                        html+='<div class="list" data='+res.data[i].store_id+'>'+res.data[i].store_name+'</div>'
                      }
                      $(".storeboxCopy").show();
                      $('.storeboxCopy').html('');
                      $('.storeboxCopy').append(html);
                    }
                  },"json");
        }
      });

      $(".storeboxCopy").on("click",".list",function(){
        $('.inputstoreCopy').val($(this).html());
        $('.store_idCopy').val($(this).attr('data'));
        $('.storeboxCopy').hide();
      });

      // 一键复制
      $('.addPlGoods').click(function(){
        if(selectedValues.length == 0){
          layer.msg('请选择商品！', {
              offset: '50px'
              ,icon: 2
              ,time: 2000
          });
          return 
        }
        if(storeSelData.length == 0){
          layer.msg('请选择门店！', {
              offset: '50px'
              ,icon: 2
              ,time: 2000
          });
          return 
        }
        var copyData = [];
        copyData = selectedValues.flatMap(item => 
          storeSelData.map(storeId => ({
            ...item,
            store_id: storeId
          }))
        );
        if(copyData.length>0){
          //执行重载
          var pageLoading = layer.msg('数据处理中..', {
                icon: 16
                ,shade: 0.3
                ,time: false
            });
          copyData.forEach((ele,index) => {
            let params = {
                token:token,
                store_id: ele.store_id,
                title: ele.title,
                img: ele.img,
                num: ele.num,
                code: ele.code,
                price: ele.price,
                status: ele.status,
                sort: ele.sort,
                store_goods_cate_id:ele.store_goods_cate_id
              }
              $.post("{{url('/api/user/add_goods')}}",
                  params,function(res){
                      if(res.status==1){
                        if(index === copyData.length - 1){
                          layer.msg(res.message, {
                              offset: '50px'
                              ,icon: 1
                              ,time: 2000
                          });
                        }
                      }else{
                          layer.msg(res.message, {
                              offset: '50px'
                              ,icon: 2
                              ,time: 2000
                          });
                      }
                  },"json");
                if(index === copyData.length - 1){ //最后一个
                    setTimeout(() => {
                        selectedIds = [];
                        selectedValues = [];
                        storeSelData = [];
                        //执行重载
                        layer.closeAll();
                        table.reload('test-table-page', {
                            where: {
                            },
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        
                    }, 2000);
                }
          });
        }
      });

      // 商品分类
      $('#goodsCate').click(function(){
        table.render({
            elem: '#cateTable'
            ,height:480
            ,url: "{{url('/api/user/goods_cate')}}"
            ,method: 'get'
            ,where:{
                token:token,
                cur:1
            }
            ,request:{
                pageName: 'p',
                limitName: 'l'
            }
            ,page: true
            ,cols: [[
                {field: 'id', title: 'id', width: 200}
                ,{field: 'title',  title: '分类名称',width: 200}
                ,{width: 150, align:'center', fixed: 'right', toolbar: '#cateTable-content-list',title: '操作'}
            ]]
            ,response: {
                statusName: 'status' //数据状态的字段名称，默认：code
                ,statusCode: 1 //成功的状态码，默认：0
                ,msgName: 'message' //状态信息的字段名称，默认：msg
                ,countName: 't' //数据总数的字段名称，默认：count
                ,dataName: 'data' //数据列表的字段名称，默认：data
            }
            ,done: function(res, curr, count){
                $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
            }
        });
        layer.open({
            type: 1,
            title: '商品分类列表',
            closeBtn: 0,
            area: '600px',
            shadeClose: true,
            content: $('#openCatelist')
        });
      })

      //分类列表-编辑
      var editCate;
      table.on('tool(cateTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var e = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象

        if(layEvent === 'cateEditBtn'){
          //编辑
          $('#add_cate .cate_title').val(e.title);
          $('#add_cate #cateId').val(e.id);
          editCate = layer.open({
              type: 1,
              title: '编辑商品分类',
              closeBtn: 0,
              area: '516px',
              skin: 'layui-layer-nobg', //没有背景色
              shadeClose: true,
              content: $('#add_cate')
          });
        }
      })

      //添加商品分类
      var addCate;
      $('.buildCate').click(function(){
          $('#add_cate .cate_title').val('');
          $('#add_cate #cateId').val('');
          addCate = layer.open({
              type: 1,
              title: '添加商品分类',
              closeBtn: 0,
              area: '516px',
              skin: 'layui-layer-nobg', //没有背景色
              shadeClose: true,
              content: $('#add_cate')
          });
      })
      
      //添加商品分类-提交
      $('.cateSubmit').click(function(){
            var index = layer.load(2);
            let id = $('#add_cate #cateId').val();
            let params = {
                token:token
                ,title:$('#add_cate .cate_title').val()
            }
            if(id){
              params['id'] = id
            }
            $.post("{{url('/api/user/add_goods_cate')}}",
                params,
                function(res){
                    //console.log(res);
                    layer.close(index);

                    if(res.status==1){
                        layer.msg('提交成功', {
                            offset: '50px'
                            ,icon: 1
                            ,time: 2000
                        },function(){
                            layer.close(addCate)
                            // layer.closeAll();
                           //执行重载
                           let pageParams = {
                              curr: 1
                           }
                           if(id){
                            pageParams = {}
                            layer.close(editCate)
                           }
                            table.reload('cateTable', {
                              pageParams,
                              where: {}
                            });
                        });
                    }else{
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 2
                            ,time: 3000
                        });
                    }
                },"json");
        })

        // 选择数据来源
        form.on('select(scource)', function(data){
            var scource = data.value;
            $('.scource').val(scource);
            console.log(data,'scource')
            let params = {}
            if(scource == 1){ //商品信息库
              $('.storename').hide()
              // $('.batchDel').hide()
              // $('.plCopy').show()
              // params = {
              //   store_id:-1,
              //   token:token
              // }
            }else{
              $('.storename').show()
              // $('.batchDel').show()
              // $('.plCopy').hide()
              // params = {
              //   store_id:$('.store_id').val(),
              //   token:token
              // }
            }
            form.render()
            //执行重载
            // tableIns.reload( {
            //     where: params
            //     ,page: {
            //         curr: 1
            //     }
            // });
        });

      // 批量修改
      $('#batchEdit').click(function(){
        $('.importstore').val('');
        $('.store_id_import').val('');
        batchEditModal = layer.open({
          type: 1,
          title: '门店商品批量修改-选择门店',
          closeBtn: 1,
          area: '600px',
          skin: 'layui-layer-nobg', //没有背景色
          shadeClose: true,
          content: $('#open_import'),
          success:function(){
            
          }
        });
      })

      $(".importstore").bind("input propertychange",function(event){
        let store_name = $(this).val();
        if (store_name.length == 0) {
          $('.importstorebox').html('');
          $('.importstorebox').hide();
        } else {
          $.post("{{url('/api/user/store_lists')}}",
                  {
                    token:token
                    ,store_name:$(this).val()
                    ,l:100
                  },function(res){
                    $('.importstorebox').html('');
                    var html="";
                    if(res.t==0){
                      $('.importstorebox').html('');
                    }else{
                      for(var i=0;i<res.data.length;i++){
                        html+='<div class="list" data='+res.data[i].store_id+'>'+res.data[i].store_name+'</div>'
                      }
                      $(".importstorebox").show();
                      $('.importstorebox').append(html);
                    }
                  },"json");
        }
      });

      $(".importstorebox").on("click",".list",function(){
        $('.importstore').val($(this).html());
        $('.store_id_import').val($(this).attr('data'));
        $('.importstorebox').hide();
      });

      // 选择门店后-获取门店下的商户数据
      var storeGoodsData = [];
      var tableData = [];
      var filelist = []; //导入文件
      $('.batchEditStore').click(function(){
        storeGoodsData = [];
        tableData = [];
        filelist = [];
        $('.uploadFile').html('选择所需上传文件')
        $('#file').val('')
        let store_id = $('.store_id_import').val()
        if(store_id){
          $.post("{{url('/api/user/goods_list')}}",
            {
              token:token,
              store_id:store_id,
              l:500
            },function(res){
              var html="";
              if(res.t==0){
                layer.msg('当前门店下暂无商品数据！')
              }else{
                storeGoodsData = res.data || [];
                var batchEditTable = layer.open({
                    type: 1,
                    title: '批量修改数据',
                    area:  ['800px','800px'],
                    content: $('#exportTable'),
                    success: function(){
                        // 渲染表格
                        table.render({
                            elem: '#previewTable',
                            data: tableData,
                            cols: [[
                              // 序号列
                              {field: 'code', title: '商品编码',width:240,
                                templet: function(d){
                                  console.log(d.isAdd)
                                  // 在这里定义输入框模板
                                  // if(d.isAdd && d.isAdd == true){
                                    return '<div style="display:flex;align-items: center;margin-left: -15px;margin-right: -15px;"><input type="text" name="code" value="' + d.code + '" data-index="'+d.indexData+'" lay-verify="required" placeholder="请输入内容" class="layui-input addcode"><button data-index="'+d.indexData+'" class="layui-btn layui-btn-xs" style="margin-left:6px" lay-event="getCodeStore">获取商品</button></div>';
                                  // }else{
                                  //   return d.code
                                  // }
                                  
                                }},
                              {field: 'title', title: '商品标题'},
                              {field: 'price', title: '原价格'},
                              {field: 'newprice', title: '新价格(可编辑)',edit:'text'},
                              // 操作列
                              {title: '操作', width: 125, toolbar: '#operateTpl'}
                            ]],
                            page: true,
                            limit: 2000,
                            height:520,
                            scroll: { // 开启横向滚动条
                              y: 500 // 横向滚动区域宽度，跟容器宽度一样
                            },
                            done: function(res, curr, count){
                              // $('tr').css({'height': '50px', 'line-height': '50px'});	//进行表头样式设置
                              $('#exportTable .layui-table-cell').css({'height': '40px', 'line-height': '40px'});	//进行表头样式设置
                              $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
                            }
                        });
                    },
                    cancel: function(index, layero){ 
                      layer.close(index)
                    }  
                });
              }
            },"json");
          
      }
      })

      // 导入批量修好数据
      $('.uploadFile').click(function(){
        $("#file").click();
      })
      // 获取文件名
      var file = $('#file');
      file.on('change', function( e ){
          //e.currentTarget.files 是一个数组，如果支持多个文件，则需要遍历
          var name = e.currentTarget.files[0].name;
          filelist = e.currentTarget.files;
          console.log( name );
          console.log(  e.currentTarget.files );
          $('.uploadFile').html(name);
      });

      var tableData = [];
      $('#UploadData').click(function(){
        var formData = new FormData($( "#uploadForm" )[0]); 
        console.log(formData,'formData')
        console.log(filelist,'filelist--')
        //导入确认弹框
        var uploadFile = filelist[0];
        if(!uploadFile) return;
        console.log(uploadFile,'uploadFile----')
        var reader = new FileReader();
        var headers = [];
        let nodatacode = '';
        let hasdatacode = '';
        reader.onload = function(e) {
          var extension = uploadFile.name.split('.').pop().toLowerCase();
          const headerMap = {
            '商品编码':'code',
            '价格':'newprice',
          }
          if (extension === 'xlsx' || extension === 'xls' || extension === 'csv') {
            let data = new Uint8Array(e.target.result);
            let workbook = XLSX.read(data, {type: 'array'});
            
            // 获取第一个工作表的数据
            let firstSheet = workbook.Sheets[workbook.SheetNames[0]];
            let jsonData = XLSX.utils.sheet_to_json(firstSheet, {header:1});
            console.log(jsonData,'jsonData--')
            
            // 转换表头和数据
            headers = jsonData[0];
            let tableTempData = jsonData.slice(1).map(function(row,index){
                var obj = {
                  // indexData: index+1, // 生成唯一ID
                  uploaded: false           // 上传状态
                };
                headers.forEach(function(header, index){
                  const enField = headerMap[header] || header; // 保留未映射的原始字段
                  obj[enField] = row[index];
                });
                return obj;
            });
            tableTempData.forEach((ele,index)=>{
              let findindex = storeGoodsData.findIndex(item=>item.code == ele.code)
              if(ele.code && findindex>-1){
                console.log(storeGoodsData[findindex],'storeGoodsData[findindex]')
                let hasindex = tableData.findIndex(itemTemp=>itemTemp.code == ele.code)
                if(hasindex === -1){
                  const mergedObj = { ...ele,...storeGoodsData[findindex],indexData:index}
                  tableData.push(mergedObj)
                }else{
                  hasdatacode += `${ele.code},`
                }
                
              }else{
                if(ele.code){
                  nodatacode += `${ele.code},`
                }
                
              }
            })
            getTableData()
            console.log(tableData,'tableData---')
            
            if(nodatacode || hasdatacode){
              let layerContent = ''
              if(nodatacode){
                layerContent = `${nodatacode}在当前门店下无数据`
              }
              if(hasdatacode){
                layerContent += `<br>${hasdatacode}在列表中已存在`
              }
              layer.open({
                  title:'提示',
                  content: layerContent,
                  yes: function(index, layero){
                      //do something
                      layer.close(index); //如果设定了yes回调，需进行手工关闭
                  }
              }); 
            }
            // 刷新表格
            table.reload('previewTable', {
              data: tableData,
            });
          } else {
              layer.msg('仅支持上传 XLSX/XLS 或 CSV 文件');
              return;
          }
        };
        reader.readAsArrayBuffer(uploadFile);
      })

      // 新增修改表格
      $('.addbatchEdit').click(function(){
        
        // getTableData()
        let length = tableData.length;
        let obj = {
          uploaded: false,
          isAdd:true,
          code:'',
          indexData:length,
          newprice:''
        }
        tableData.push(obj)
        // 刷新表格
        table.reload('previewTable', {
          data: tableData,
        });
        console.log(tableData,'tableData------addbatchEdit')
      })

      // 监听工具条
      table.on('tool(previewTable)', function(obj){
        var data = obj.data; // 获得当前行数据
        if(obj.event === 'getCodeStore'){
          console.log('获取商品')
          console.log(obj)
          // let dataindex = $(this).data('index')
          // $('.addcode').eq(dataindex).value();
          console.log($('.addcode'))
          let inds = obj.data.indexData;
          let storeCode = $('.addcode')[inds].value;
          if(storeCode){
            let findindex = storeGoodsData.findIndex(ele=>ele.code === storeCode)
            if(findindex>-1){
              let findins = tableData.findIndex(ele=>ele.code===storeCode)
              if(findins===-1){
                tableData[inds] = {...data,...storeGoodsData[findindex]}
                // 刷新表格
                getTableData()
                table.reload('previewTable', {
                    data: tableData,
                });
              }else{
                layer.msg('此编码在列表中已存在，请勿重复添加！')
              }
              
            }else{
              layer.msg('此编码在当前门店下无数据！')
            }
          }else{
            layer.msg('请先输入商品编码！')
          }

        }else if(obj.event === 'delClick'){
          layer.confirm('确认移除此商品?',{icon: 2}, function(index){
            console.log(data.indexData,'11111')
            tableData = tableData.filter(ele=>ele.indexData !== data.indexData)
            // 刷新表格
            getTableData()
            table.reload('previewTable', {
                data: tableData,
            });
            layer.close(index);
            layer.msg('已移除', {
              offset: '50px'
              ,icon: 1
              ,time: 1000
            });
            });
        }else if(obj.event === 'editClick'){
          console.log(data,'编辑的数据---')
          console.log(Number(data.newprice),'newprice---')
          if(data.newprice && !Number.isNaN(Number(data.newprice)) && data.id){
            let { title,num,code,sort,store_id,img,status,store_goods_cate_id,id } = data;
            let params = {
              token:token,title,num,code,sort,store_id,img,status,store_goods_cate_id,id,price:data.newprice,
            }
            $.post("{{url('/api/user/add_goods')}}",
            params,function(res){
                if(res.status==1){
                    layer.msg('修改成功', {
                        offset: '50px'
                        ,icon: 1
                        ,time: 3000
                    });
                    tableData[data.indexData].uploaded = true;
                    // 刷新表格
                    table.reload('previewTable', {
                        data: tableData,
                    });
                }else{
                    layer.msg(res.message, {
                        offset: '50px'
                        ,icon: 2
                        ,time: 3000
                    });
                }
            },"json");
          }else{
            layer.msg('请检查无误后再提交！')
          }
        }
      });

      function getTableData(){
        
        tableData = tableData.map((item,index)=>{
          return {...item,indexData:index}
        })
        console.log(tableData,'getTableData-----')
      }

      // 批量修改-新价格可编辑
      table.on('edit(previewTable)', function (obj) {
        var data = obj.data //得到所在行所有数据
        var value = obj.value; // 得到修改后的值
        var field = obj.field; // 得到字段
        console.log(field,'field')
        if(field === 'newprice'){
          // 验证输入是否为数字且最多2位小数
          var regex = /^\d+(\.\d{1,2})?$/;
          if(!regex.test(value)) {
            layer.msg('请输入有效的数字，最多2位小数');
            return false;
          }
          if(value){
            // 当价格修改时，更新
            table.reload('previewTable', {
              data: table.cache.previewTable
            });
            console.log(table.cache.previewTable,tableData)
            tableData = [...table.cache.previewTable]
          }
        }
      })

      // 一键修改
      $('.batchUploadEdit').click(function(){
        if(tableData.length>0){
          const isValid = tableData.every(item => 
            item.newprice && 
            !Number.isNaN(Number(item.newprice)) && 
            item.id
          );
          console.log(isValid,'isValid')
          if(isValid === true){
          
            //执行重载
            var editLoading = layer.msg('数据处理中..', {
                icon: 16
                ,shade: 0.3
                ,time: false
            });
            tableData.forEach((data,index) => {
              if(data.newprice && !Number.isNaN(Number(data.newprice)) && data.id){
                  let { title,num,code,sort,store_id,img,status,store_goods_cate_id,id } = data;
                  let params = {
                    token:token,title,num,code,sort,store_id,img,status,store_goods_cate_id,id,price:data.newprice,
                  }
                  $.post("{{url('/api/user/add_goods')}}",
                  params,function(res){
                      if(res.status==1){
                        tableData[data.indexData].uploaded = true;
                        if(index === tableData.length - 1){
                          layer.msg('修改成功', {
                              offset: '50px'
                              ,icon: 1
                              ,time: 3000
                          });
                          setTimeout(() => {
                            // 刷新表格
                            table.reload('previewTable', {
                                data: tableData,
                            });
                          }, 1000);
                        }
                      }else{
                          layer.msg(res.message, {
                              offset: '50px'
                              ,icon: 2
                              ,time: 3000
                          });
                      }
                  },"json");
                }
            });
            
          }else{
            layer.msg('请检查无误后再提交！')
            return false
          }
        }
      })

      // 批量删除
      $('#batchDel').click(function(){
        if(selectedIds.length == 0){
          layer.msg('请选择商品！', {
              offset: '50px'
              ,icon: 2
              ,time: 2000
          });
          return 
        }
        if(selectedIds.length>0){
          layer.confirm('确认删除选择的所有商品吗?',{icon: 2}, function(index){
            //执行重载
          var batchDelLoading = layer.msg('数据处理中..', {
                icon: 16
                ,shade: 0.3
                ,time: false
            });
          selectedIds.forEach((ele,index) => {
            $.ajax({
              url : "{{url('/api/user/del_goods')}}",
              data : {token:token,id:ele},
              type : 'post',
              success : function(data) {
                if(data.status==1){
                  if(index === selectedIds.length - 1){
                    layer.msg(data.message, {
                        offset: '50px'
                        ,icon: 1
                        ,time: 2000
                    });
                  }
                }else{
                  layer.msg(data.message, {
                    offset: '50px'
                    ,icon: 2
                    ,time: 3000
                  });
                }
                  
              },
            });
            if(index == selectedIds.length - 1){
              setTimeout(() => {
                  selectedIds = [];
                  selectedValues = [];
                  storeSelData = [];
                  //执行重载
                  layer.closeAll();
                  table.reload('test-table-page', {
                      where: {
                        store_id:$('.store_id').val(),
                      },
                      page: {
                          curr: 1 //重新从第 1 页开始
                      }
                  });
                  
              }, 3000);
            }
                
          });
          });
          
        }
      })
      
    });


  </script>

</body>
</html>